<template>
  <a-card :bordered="false">
    <h3>用户列表</h3>
    <UserListFilter
      ref="filter"
      :productVisible.sync="productVisible"
      :productList="productList"
      :isMaterialTools="true"
      @onExport="handleExport"
      @onImportSuccess="onImportSuccess"
      @onDownload="handleDownload"
      @onAddOfficialNo="handleAddOfficialNo"
      @onSearch="onSearch"
    ></UserListFilter>
    <a-tabs v-model="activeKey" @change="tabChange">
      <a-tab-pane v-for="item in tabList" :tab="item.name" :key="item.id"></a-tab-pane>
    </a-tabs>
    <s-table ref="table" bordered size="default" :rowKey="record => record.id" :columns="columns" :data="loadData" :pagination="paginationProps" :scroll="{ x: 1300 }" :key="activeKey">
      <span slot="status" slot-scope="text, record">
        <span v-if="record.status == 1">禁用</span>
        <span v-if="record.status == 0">正常</span>
      </span>
      <span slot="isPromote" slot-scope="text, record">
        <span v-if="record.isPromote == 0">允许</span>
        <span v-if="record.isPromote == 1">不允许</span>
      </span>
      <a slot="passContent" slot-scope="text, record" @click="contentList(record.communityId)">{{ record.passContent }}/{{ record.totalContent }}</a>
      <a slot="awardTopic" slot-scope="text, record" @click="contentList(record.communityId, 123)" >{{ record.awardTopic }}/{{ record.totalTopic }}</a>
      <span slot="disabledContent" slot-scope="text, record">{{ record.disabledContent }}/{{ record.totalContent }}</span>
      <span slot="disableComment" slot-scope="text, record">{{ record.disableComment }}/{{ record.totalComment }}</span>
      <span slot="disabledContentPercent" slot-scope="text, record">{{ record.disabledContentPercent }}%</span>
      <span slot="disableCommentPercent" slot-scope="text, record">{{ record.disableCommentPercent }}%</span>
      <span slot="totalAccountDisable" slot-scope="text, record">
        <!-- <span v-if="record.totalAccountDisable < 1">{{ record.totalAccountDisable }}</span>
            v-else -->
        <a v-if="record.totalAccountDisable > 0" @click="handleExamineDisableInformation(record)">{{ record.totalAccountDisable }}</a>
        <span v-else>{{ record.totalAccountDisable }}</span>
      </span>
      <span slot="action" slot-scope="record">
        <a v-if="record.status == 0" @click="handleUserAddDisable(record.id)">禁用</a>
        <a-popconfirm v-if="record.status == 1" ok-text="确定" cancel-text="暂不" title="确认要启用该账号吗？" @confirm="handleUserRecover(record.id)">
          <a>启用</a>
        </a-popconfirm>
        <a-divider type="vertical" />
        <a v-if="activeKey == 1" @click="handleEditOfficialNo(record)">编辑</a>
        <a v-else @click="handleEditUserNo(record)">编辑</a>
      </span>
    </s-table>
    <a-modal title="禁用原因" :visible="disableReasonVisible" width="500px" @ok="handleSubmit" @cancel="disableReasonVisible = false">
      <a-form-model ref="rulesForm" :model="form" :rules="rules" layout="vertical">
        <a-form-model-item label="禁用原因" prop="whyName">
          <a-checkbox-group v-model="form.whyName">
            <a-checkbox v-for="item in whyList" :value="item.whyName" :key="item.id">{{ item.whyName }}</a-checkbox>
          </a-checkbox-group>
        </a-form-model-item>
        <a-form-model-item label="备注（选填）">
          <a-textarea v-model="form.disableNote" :rows="4" :maxLength="60" placeholder="限60个字符以内" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <a-modal title="" :visible="disableInformationVisible" width="800px" :footer="null" @cancel="disableInformationVisible = false">
      <a-descriptions title="禁用信息">
        <a-descriptions-item label="用户昵称">{{ disableInformation.userNickname }}</a-descriptions-item>
        <a-descriptions-item label="社区id">{{ disableInformation.communityId }}</a-descriptions-item>
        <a-descriptions-item label="">该账号共被禁用{{ disableInformation.totalAccountDisable }}次</a-descriptions-item>
      </a-descriptions>
      <a-table :pagination="pagination" :columns="disableInformationColumns" :data-source="userDisableList" :rowKey="(record, index) => index" @change="handleDisableInformationChange"> </a-table>
    </a-modal>
  </a-card>
</template>
<script>
import { userPage, userRecover, userAddDisable, whyPage, userDisable, exportUserList, templateDownload, userTypeCount, identityList } from '@/api/micromall/communityUser'
import { STable } from '@/views/box/components'
import UserListFilter from '../../components/UserListFilter'
import { userColumns, guideColumns, creatorColumns, officialColumns } from './userList.js'
import { mapGetters } from 'vuex'
const disableInformationColumns = [
  {
    title: '禁用原因',
    align: 'center',
    width: '140px',
    dataIndex: 'whyName'
  },
  {
    title: '备注',
    align: 'center',
    width: '140px',
    dataIndex: 'disableNote'
  },
  {
    title: '禁用时间',
    align: 'center',
    width: '140px',
    dataIndex: 'createTime'
  },
  {
    title: '禁用人',
    align: 'center',
    width: '140px',
    dataIndex: 'disableUserName'
  }
]
let tabList = [
]

export default {
  components: {
    UserListFilter,
    STable
  },
  data() {
    return {
      sort: { createTime: 0 },
      filters: {},
      id: '',
      userDisableList: [],
      disableInformation: {},
      userId: '',
      whyList: [],
      disableInformationColumns,
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
        showTotal: total => `共有 ${total} 条数据`
      },
      form: {
        whyName: []
      },
      rules: {
        whyName: [{ required: true, message: '请选择', trigger: 'change' }]
      },
      disableInformationVisible: false,
      disableReasonVisible: false,
      productVisible: false,
      imgCurrent: 0,
      imgVisible: false,
      imgs: [],
      productList: [],
      tabList: [],
      activeKey: 1,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      columns: officialColumns,
      paginationProps: {
        total: 0,
        showTotal: total => `共有 ${total} 条数据`
        // onShowSizeChange: (current, pageSize) => this.changePageSize(current, pageSize)
      },
      queryParam: {},

      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        if (this.requestFlag()) return
        if (parameter.sortOrder) {
          this.sort = {}
          this.sort[parameter.sortField] = parameter.sortOrder == 'descend' ? 0 : 1
        } else {
          delete this.sort[parameter.sortField]
        }
        this.tableFilters(parameter)
        const data = {
          ...this.filters,
          ...this.queryParam,
          current: parameter.pageNo,
          size: parameter.pageSize,
          identityId: this.activeKey,
          ...this.sort
        }
        return userPage(data).then(res => {
          if (res.code === 200) {
            const { records, total, size, current } = res.data
            const data = {
              page: {
                count: total,
                pageNo: current,
                pageSize: size,
                pages: Math.ceil(total / size)
              },
              data: records
            }
            return data
          } else {
            this.$message.error(res.msg || res.message)
            const data = {
              page: {
                count: 0,
                pageNo: 0,
                pages: 0
              },
              data: []
            }
            return data
          }
        })
      }
    }
  },
  created() {
  },
  computed: {},
  mounted() {},
  activated() {
    // this.getCount()
    this.getIdentityList()
    this.getWhyPage()
    
  },
  watch: {
    $route(to, from) {
      const whiteList = [
        '/micromall/community/userManagement/addOrEditOfficialNo',
       '/micromall/community/userManagement/editUserNo',
       '/micromall/community/contentManagement/contentList'
       ]
      const currentPathBase = '/micromall/community/userManagement/userList'
      const currentPath = this.$route.path
      if (this.checkRoute(from.path, whiteList) && to.path.includes(currentPathBase)) {
        this.$refs.table.refresh() // 刷新当前列表（记录上次页码）
      } else {
        if (currentPath.includes(currentPathBase)) {
          if (this.activeKey == 1) {
            this.activeKey = 2
            this.tabChange(this.activeKey) // 刷新当前页面
          }
          const that = this
          setTimeout(() => {
            that.activeKey = 1
            that.tabChange(that.activeKey) // 刷新当前页面
          }, 1)
        }
      }
    }
  },
  methods: {
    requestFlag() {
      const currentPathBase = '/micromall/community/userManagement/userList'
      const currentPath = this.$route.path
      if (!currentPath.includes(currentPathBase)) return true
      return false
    },

    // 获取身份标识
    getIdentityList() {
      identityList({}).then(res => {
        if (res.code === 200) {
          this.tabList = res.data.reverse().map(e => {
            return {
              ...e,
              name: '加载中'
            }
          })
          this.getCount()
        } else {
          this.$message.error(res.msg || res.message)
        }
      })
    },

    // 列表filters
    tableFilters(parameter) {
      this.columns.filter(e => e.filters).map(e => e.dataIndex).forEach(key => {
          if (parameter[key]) {
            if (parameter[key].length) {
              this.filters[key] = parameter[key][0]
            } else {
              delete this.filters[key]
            }
          }
      })
    },

    // 内容列表
    contentList(communityId, jumps) {
      if (jumps) {
        this.$router.push(`/micromall/community/contentManagement/contentList?communityId=${communityId}&jumps=${jumps}`)
      } else {
        this.$router.push(`/micromall/community/contentManagement/contentList?communityId=${communityId}`)
      }
    },

    // // 话题列表
    // topicList(communityId) {
    //   this.$router.push(`/micromall/community/contentManagement/topicList?communityId=${communityId}`)
    // },


    // 获取状态数量
    getCount() {
      if (this.requestFlag()) return
      userTypeCount({}).then(res => {
        if (res.code === 200) {
          Object.keys(res.data).forEach(e => {
            this.tabList.forEach(i => {
              if (i.id == e) {
                i.name = `${i.identityName}（${res.data[e] || 0}）`
              }
            })
          })
        } else {
          this.$message.error(res.msg || res.message)
        }
      })
    },

    tabChange(activeKey) {
      this.sort = { createTime: 0 }
      this.filters = {}
      this.activeKey = activeKey
      switch (activeKey) {
        case 2:
          // 用户
          this.columns = userColumns
          break
        case 3:
          // 导购
          this.columns = guideColumns
          break
        // case '4':
        //   // 创作者
        //   this.columns = creatorColumns
        //   break
        case 1:
          // 官方账号
          this.columns = officialColumns
          break
        default:
          this.columns = creatorColumns
      }
      this.$refs.filter.reset()
    },

    // 查看账号禁用情况
    handleExamineDisableInformation(item) {
      this.disableInformation = item
      this.userDisableList = []
      this.id = item.id
      this.pagination.current = 1
      this.getUserDisable()
      this.disableInformationVisible = true
    },

    // 查询用户被禁用记录
    getUserDisable() {
      const data = {
        id: this.id,
        current: this.pagination.current,
        size: this.pagination.pageSize
      }
      userDisable(data).then(res => {
        if (res.code === 200) {
          const { records, total } = res.data
          this.userDisableList = records
          const pagination = { ...this.pagination }
          pagination.total = total
          this.pagination = pagination
        } else {
          this.$message.error(res.msg || res.message)
        }
      })
    },

    // 导出
    handleExport() {
      window.location.href =  exportUserList + `?identityId=${this.activeKey}`
    },

    // 禁用原因
    getWhyPage() {
      if (this.requestFlag()) return
      const data = {
        type: 4,
        status: 0
      }
      whyPage(data).then(res => {
        if (res.code === 200) {
          this.whyList = res.data.records
        } else {
          this.$message.error(res.msg || res.message)
        }
      })
    },

    // 启用
    handleUserRecover(userId) {
      const data = {
        userId
      }
      userRecover(data).then(res => {
        if (res.code === 200) {
          this.$refs.table.refresh()
          this.getCount()
        } else {
          this.$message.error(res.msg || res.message)
        }
      })
    },

    // 禁用
    handleUserAddDisable(userId) {
      this.userId = userId
      this.disableReasonVisible = true
    },

    //  下载导入模板
    handleDownload() {
      window.location.href = 'https://jnbyoss.oss-cn-hangzhou.aliyuncs.com/upload/20220829/92f790c5993eec2434f1d2c8c02005ef.xlsx'
    },

    // 批量导入成功
    onImportSuccess() {
      this.$refs.table.refresh()
      this.getCount()
    },

    checkRoute(fromPath, routeArr) {
      for (let i = 0; i < routeArr.length; i++) {
        if (fromPath.includes(routeArr[i])) {
          return true
        }
      }
      return false
    },
    
    // 替换特殊字符
    formatObj(values) {
      if (Object.prototype.toString.call(values) !== '[object Object]') {
        return values
      }
      let formValue = JSON.parse(JSON.stringify(values))
      Object.keys(formValue).forEach(i => {
        if ((typeof formValue[i]=='string')&&formValue[i].constructor==String) {
          formValue[i] = formValue[i].replace(/\%/g, "%25")
          formValue[i] = formValue[i].replace(/\#/g, "%23")
        } else if (Array.isArray(formValue[i])) {
          formValue[i] = formValue[i].map(e => {
           return (typeof e == 'object' && !Array.isArray(e)) ? this.formatObj(e) : e
          })
        }
      })
      return formValue
    },

    // 新增官方账号
    handleAddOfficialNo(e) {
      this.$router.push(`/micromall/community/userManagement/addOrEditOfficialNo?item=${e}`)
    },

    // 编辑官方账号
    handleEditOfficialNo(e) {
      const item = encodeURIComponent(JSON.stringify(this.formatObj(e)))
      this.$router.push(`/micromall/community/userManagement/addOrEditOfficialNo?item=${item}`)
    },

    // 编辑其他类账号
    handleEditUserNo(e) {
      const item = encodeURIComponent(JSON.stringify(this.formatObj(e)))
      this.$router.push(`/micromall/community/userManagement/editUserNo?item=${item}`)
    },

    //查询
    onSearch(obj) {
      this.queryParam = obj
      this.$refs.table.refresh(true)
    },

    handleDisableInformationChange(pagination) {
      const pager = { ...this.pagination }
      pager.current = pagination.current
      this.pagination = pager
      this.getUserDisable()
    },

    ...mapGetters(['nickname', 'avatar', 'userInfo']),

    // 禁用
    handleSubmit() {
      this.$refs.rulesForm.validate(valid => {
        if (valid) {
          const { disableNote, whyName } = this.form
          const data = {
            userId: this.userId,
            disableNote: disableNote,
            whyName: whyName.join(','),
            disableUserId: this.userInfo().id,
            disableUserName: this.userInfo().realname
          }
          this.disableReasonVisible = false
          userAddDisable(data).then(res => {
            if (res.code === 200) {
              this.form = {}
              this.$refs.table.refresh()
              this.getCount()
            } else {
              this.$message.error(res.msg || res.message)
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
/deep/.ant-checkbox-wrapper {
  margin-left: 0;
  margin-right: 8px;
}
</style>
